import { getCategory } from '@/api/products';
import { ref, computed } from 'vue'
import { useRequest } from 'vue-request';

export const useCategory = () => {
    //请求数据
    // const categoryTree = ref([])

    // const _getCategory = async () => {
    //     categoryTree.value = await getCategory().then(res => res.data.data)
    // }
    // _getCategory();

    //data:接口请求到的数据,
    const {data:categoryTree,loading} = useRequest(getCategory,{
        cacheKey:'category',
        staleTime:2*60*1000
        
    });




    //懒加载
    const load = (row, treeNode, resolve) => {
        // console.log('加载执行');
        // console.log(row.children);
        setTimeout(() => {
            resolve(row.children);
        }, 500)
    }


    //分类:产品中有个：categoryId,通过该字段，找到所属分类
    //树转列表
    function treeToList(tree, result = [], parent = null) {
        tree.forEach(item => {
            //浅拷贝，防止操作影响源数据
            const element = { ...item };
            //添加parentId属性
            element.parentId = parent;

            result.push(element);
            if (element.children) {
                treeToList(element.children, result, element.id);
            };
            delete element.children;
        });

        return result;
    }

    const categoryList = computed(() => treeToList(categoryTree.value));
    //转哈希表
    const categoryMap = computed(() => categoryList.value.reduce((prev, curr) => ((prev[curr.id] = curr), prev), {}));


    //查找分类
    function getCategoryPath(cId,result=[]) {
        //找到当前分类
        const _category = categoryList.value.find((obj)=> obj.id==cId);
        if(_category){
            
            result.unshift(_category);
            //查看是否有父节点，如果有，递归调用
            if(_category.parentId){
                getCategoryPath(_category.parentId,result);
            }
        }

        return result;
    }



    return {
        categoryTree,
        categoryList,
        categoryMap,
        getCategoryPath,
        loading,
        load
    }
}